# React-Router
Router算是学完了,怎么说呢一言难尽,技术胖这个胖子讲的太皮毛了。对有一定开发经验的人不太友好。还得自己研究。既然看了那就搞他妈的。
整体上来看,乱,是给我的第一映像,路由的嵌套更是让人觉得无法维护。
# 基本用法
# 通过标签跳转
import {BrowserRouter as Router, Route} from 'react-router-dom'
const Nav = (props) => {
return (
<Router>
<Link to='/' />
<Route path='/' component={componentName} />
</Router>
)
};
# 通过函数跳转
this.props.history.push('/')
# 传递参数
<Router>
<Link to='/index/123' />
<Route path='/index/:id' component={componentName} />
</Router>
# 获取参数
const { id } = this.props.match.params
# 常用属性
- BrowserRouter
- HashRouter
- Route
- Link - 跳转
- Redirect - 重定向
- Switch - 匹配到一个就停,防止匹配到多个路由
- exact - 完全匹配
# 路由嵌套
页面A - 跳转 - 页面B - 跳转 - 页面C
// A.js
const A = (props) => {
return (
<Router>
<Link to='/B' />
<Route path='/B' component={B} />
</Router>
)
};
// B.js
const A = (props) => {
return (
<Router>
<Link to='/B/C' />
<Route path='/B/C' component={C} />
</Router>
)
};
# ???
这玩意怎么这么难受,怎么封装谁能告诉我~
找到了一个例子,先放在着
- 配置文件 /assets/js/router.js
import Home from '../../components/Home';
import ProductDetail from '../../components/ProductDetail';
import User from '../../components/User';
import Main from '../../components/User/Main';
import Info from '../../components/User/Info';
let router = [
{
path: '/',//首页默认加载的页面
componentName: Home,
exact: true //是否为严格模式
},
{
path: '/productdetail/:id',//后面是传递的参数id
componentName: ProductDetail
},
{
path: '/user',
componentName: User,
routes: [ /** 嵌套路由 User下面又有两个子页面*/
{
path: '/user/',
componentName: Main,
exact: false
},
{
path: '/user/info',
componentName: Info
},
]
}
];
export default router;
2.在App.js入口文件引入router.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import router from './assets/js/router';
class App extends Component {
render() {
return (
<Router>
<div className="App">
{
router.map(({path, componentName, exact = true, routes = []}, key) => {
return <Route
exact={exact}
key={key}
path={path}
render={props => (
//主要是为了传递嵌套路由到子组件
//类似于 <User {...props} routes={routes} />
<componentName {...props} routes={routes} />
)}
/>
})
}
</div>
</Router>
);
}
}
export default App;
- 在user.js文件根据routers获取嵌套路由
import React, { Component } from 'react';
import { Route, Link } from "react-router-dom";
class User extends Component {
constructor(props) {
super(props);
}
render() {
let {match, routes} = this.props;
return (
<div>
<div className="content">
<div className="left">
<Link to={`${match.url}`}>个人中心</Link>
<br/>
<Link to={`${match.url}/info`}>用户信息</Link>
</div>
<div className="right">
{
routes.map(({path, componentName, exact = true},key) => {
return <Route
exact={exact}
key={key}
path={path}
component={componentName}
/>
})
}
</div>
</div>
</div>
);
}
}
export default User;
# End
也就是说Route我可以在任何地方声明,不影响我使用?
← React - 04 Redux - 01 →